">Enjoy extra content such as animations and movies,RSS,music and blog.. travels, recipes, prose, and climate science." name="description">" property="og:description">
Function annotations and type hints, introduced in Python 3, provide a way to add metadata to function arguments and return values. While they don't enforce types at runtime in standard Python, they are invaluable for static analysis tools (like MyPy), linters, and for improving code readability and maintainability by clearly indicating the expected types.
"""Greets a person with a specified greeting.
SSigLabs Code
Args:
"""
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Greetings"))
Returns:
A dictionary where keys are string representations of numbers
and values are their counts in the input list.
Lesson 04
"""
Files, errors, and testing
counts = {}
Reliable I/O and verification keep projects healthy as they grow.
# Note: Running this code with a type checker like MyPy would allow
JSON read/write
# you to catch potential type errors before runtime.
import json
Section 2: Working with Pathlib for File System Operations+
The `pathlib` module offers an object-oriented way to interact with files and directories, providing a more intuitive and readable alternative to the older `os.path` module. It encapsulates file system paths as objects, with methods for performing common operations like joining paths, checking file existence, reading/writing files, and traversing directories.
payload = {"symbol": "SIG", "price": 12.34}
from pathlib import Path
with open("data.json", "w", encoding="utf-8") as f:
json.dump(payload, f)# Get the current working directory as a Path object
current_dir = Path("./")
with open("data.json", "r", encoding="utf-8") as f:print(f"Current directory: {current_dir}")
restored = json.load(f)
print(restored)# Create a new Path object by joining parts
def pct_change(a: float, b: float) -> float:# Create the parent directories if they don't exist
if a == 0:new_file_path.parent.mkdir(parents=True, exist_ok=True)
raise ValueError("a must be non-zero")
return (b - a) / a# Write some text to the file
new_file_path.write_text("This is some data written using pathlib.\n", encoding="utf-8")
try:print(f"File written to: {new_file_path}")
pct_change(0, 10)
except ValueError as e:# Read the content of the file
print("Caught:", e)content = new_file_path.read_text(encoding="utf-8")
print(f"Content of the file:\n{content}")
Testing with pytest
# Check if a file or directory exists
# file: test_mathutils.pyprint(f"Does {new_file_path} exist? {new_file_path.exists()}")
from mathutils import pct_changeprint(f"Is {new_file_path} a file? {new_file_path.is_file()}")
print(f"Is {new_file_path.parent} a directory? {new_file_path.is_dir()}")
def test_pct_change():
assert pct_change(100, 110) == 0.10# Iterate over files in a directory with a specific extension
print("\nText files in the current directory:")
for file in current_dir.glob("*.txt"):
print(file)
Accelerate with SigLabs Financial Software
Forecasting, market screening, risk insights, and reporting—built for speed and clarity.
# new_name.parent.rmdir() # Delete the 'output.txt' directory (if empty)
# (and potentially the 'data' directory if also empty)
Section 3: Data Serialization with JSON and Pickle+
Data serialization is the process of converting Python objects into a format that can be stored or transmitted and then reconstructed later. JSON (JavaScript Object Notation) is a lightweight, human-readable format commonly used for web applications and data exchange. Pickle is a Python-specific binary format that can serialize more complex Python objects, including custom classes, but is generally not recommended for inter-system communication due to security and compatibility concerns.
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "hiking"]